package luz.javaproxy.plugins.ContentReplacer;


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.Map.Entry;

import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.LayoutStyle;
import javax.swing.WindowConstants;

import luz.javaproxy.common.Tuple;
import luz.javaproxy.plugin.PluginInterface;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.nio.entity.NFileEntity;


/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class ContentReplacer extends JPanel implements PluginInterface{
	private static final long serialVersionUID = -8006668407997259078L;
	private static final Log log = LogFactory.getLog(ContentReplacer.class);
	private ContentReplacerTable tblContentReplacer;
	private JScrollPane scrContentReplacer;
	private JButton btnAdd;
	private JButton btnRemove;
	List<Tuple<String, File>> replacerList=new LinkedList<Tuple<String, File>>();
	
	public static void main(String[] args) {
		JFrame frame = new JFrame();
		frame.getContentPane().add(new ContentReplacer());
		frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		frame.pack();
		frame.setVisible(true);
	}
	
	public ContentReplacer() {
		super();
		initGUI();
	}

	private void initGUI() {
		try {
			GroupLayout thisLayout = new GroupLayout((JComponent)this);
			this.setLayout(thisLayout);
			{
				scrContentReplacer = new JScrollPane();
				{
					tblContentReplacer = new ContentReplacerTable(replacerList);
					scrContentReplacer.setViewportView(tblContentReplacer);
				}
			}
			{
				btnAdd = new JButton();
				btnAdd.setText("Add");
				btnAdd.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) {
						tblContentReplacer.addLine();
					}
				});
			}
			{
				btnRemove = new JButton();
				btnRemove.setText("Remove");
				btnRemove.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) {
						tblContentReplacer.removeSelectedLine();
					}
				});
			}
			thisLayout.setVerticalGroup(thisLayout.createSequentialGroup()
				.addContainerGap()
				.addGroup(thisLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
				    .addComponent(btnAdd, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
				    .addComponent(btnRemove, GroupLayout.Alignment.BASELINE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE))
				.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
				.addComponent(scrContentReplacer, 0, 260, Short.MAX_VALUE));
			thisLayout.setHorizontalGroup(thisLayout.createParallelGroup()
				.addComponent(scrContentReplacer, GroupLayout.Alignment.LEADING, 0, 400, Short.MAX_VALUE)
				.addGroup(GroupLayout.Alignment.LEADING, thisLayout.createSequentialGroup()
				    .addGap(0, 234, Short.MAX_VALUE)
				    .addComponent(btnAdd, GroupLayout.PREFERRED_SIZE, 75, GroupLayout.PREFERRED_SIZE)
				    .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
				    .addComponent(btnRemove, GroupLayout.PREFERRED_SIZE, 75, GroupLayout.PREFERRED_SIZE)
				    .addContainerGap()));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	@Override
	public JPanel getPluginPanel() {
		return this;
	}
	
	@Override
	public Properties getSettings() {
		Properties p = new Properties();
		for (Tuple<String, File> element : replacerList) {
			if (!"".equals(element.getFirst()) && element.getSecond()!=null)
				p.put(element.getFirst(), element.getSecond());
		}
		return p;
	}
	
	@Override
	public void setSettings(Properties config) {
		for (Entry<Object, Object> entry : config.entrySet()) {
			replacerList.add(new Tuple<String, File>((String)entry.getKey(),new File((String)entry.getValue())));
		}
	}
	
	@Override
	public void onRequest(final HttpRequest request) {
		//nothing		
	}

	@Override
	public void onResponse(HttpRequest request, HttpResponse response) {
		String requestUri = request.getRequestLine().getUri();
		String host  = request.getFirstHeader("Host").getValue();

		for (Tuple<String, File> tuple : replacerList) {
			if (requestUri.equalsIgnoreCase(tuple.getFirst()) 
					|| ("http://"+host+requestUri).equalsIgnoreCase(tuple.getFirst()) ){
				String type = response.getFirstHeader("Content-Type").getValue();
				File file = tuple.getSecond();
				log.warn("Replaced content("+type+")"
						+"\n\tURL:  "+requestUri
						+"\n\tFile: "+file.getAbsolutePath());
				NFileEntity entity = new NFileEntity(file, type);
				response.setEntity(entity);
				break;			
			}
		}	
	}
	






}
